#ifndef __EMB_EVENT_H
#define __EMB_EVENT_H

#include "emb.h"

typedef uint8_t emb_event_t;


typedef struct{
    emb_mem_ctrl_t *Mem;
    uint16_t ReadIndex;
} emb_event_iterator_t;


static inline void emb_event_put(emb_task_id_t Id, emb_event_t Event)
{
    EMB_PORT_DISABLE_IRQ();
    emb_event_t* ptr=emb_mem_alloc(&task_table[Id].EventMem[task_table->ActiveEventMem],sizeof(emb_event_t));
    *ptr = Event;
    EMB_PORT_ENABLE_IRQ();
}

static inline int8_t _emb_event_iterator_init(emb_task_id_t Id,emb_event_iterator_t *Iterator)
{
    if(task_table[Id].EventMem[task_table->ActiveEventMem].Used!=0)
    {
        EMB_PORT_DISABLE_IRQ();
        task_table->ActiveEventMem++;
        task_table->ActiveEventMem %= 2;
        EMB_PORT_ENABLE_IRQ();

        Iterator->ReadIndex = 0;
        Iterator->Mem = &task_table[Id].EventMem[(task_table->ActiveEventMem + 1) % 2];
        return 0;
    }

    return -1;
}

static inline int8_t _emb_event_iterator_has_next(emb_event_iterator_t* Iterator)
{
    if(Iterator->ReadIndex<Iterator->Mem->Used)
    {
        return 1;
    }

    emb_mem_free(Iterator->Mem);
    return -1;
}

static inline emb_event_t _emb_event_iterator_next(emb_event_iterator_t* Iterator)
{
    emb_event_t event=*(emb_event_t*)(Iterator->Mem->Start + Iterator->ReadIndex);
    Iterator->ReadIndex += sizeof(emb_event_t);
    return event;
}

#endif
